package com.itheima.controller.system;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.itheima.controller.BaseServlet;
import com.itheima.domain.system.Permission;
import com.itheima.domain.system.Role;
import com.itheima.domain.system.User;
import com.itheima.service.impl.system.PermissionServiceImpl;
import com.itheima.service.impl.system.RoleServiceImpl;
import com.itheima.service.impl.system.UserServiceImpl;
import com.itheima.service.system.PermissionService;
import com.itheima.service.system.RoleService;
import com.itheima.service.system.UserService;
import com.itheima.utils.BeanUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/system/user/*")
public class UserServlet extends BaseServlet {

    UserService userService = new UserServiceImpl();

    RoleService roleService = new RoleServiceImpl();

    PermissionService permissionService = new PermissionServiceImpl();

    private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String pwd = req.getParameter("password");
        User user = userService.login(username, pwd);
        if (user != null && !"".equals(user)) {
            System.out.println("success");
            req.setAttribute("user", user);
            HttpSession session = req.getSession();
            session.setAttribute("user",user);
            String authorStr = "";
            List<Role> roles = user.getRoles();
            for (Role role : roles) {
                List<Permission> permissions = role.getPermissions();
                for (Permission permission : permissions) {
                    authorStr += permission.getUrl();
                }
            }
            System.out.println("========================");
            System.out.println(authorStr);
            System.out.println("========================");
            session.setAttribute("authorStr",authorStr);
            String ck = req.getParameter("ck");
            Cookie cookieName = new Cookie("username", user.getUsername());
            Cookie cookiePsd = new Cookie("pwd", user.getPassword());
            cookieName.setPath("/");
            cookiePsd.setPath("/");
            if ("1".equals(ck)) {
                cookieName.setMaxAge(7 * 24 * 3600);
                cookiePsd.setMaxAge(7 * 24 * 3600);
            } else {
                cookieName.setMaxAge(0);
                cookiePsd.setMaxAge(0);
            }


            resp.addCookie(cookieName);
            req.setAttribute("username", username);
            resp.addCookie(cookiePsd);
            req.setAttribute("pwd", pwd);
            req.getRequestDispatcher("/WEB-INF/pages/home/main.jsp").forward(req, resp);
        } else {
            req.getRequestDispatcher("/WEB-INF/pages/failer.jsp").forward(req, resp);
        }
    }

    protected void judgeEmail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String email = req.getParameter("vEmail");

        List<User> userList = userService.findAll();
        boolean flag = false;
        for (User user : userList) {
            String userEmail = user.getEmail();
            if (userEmail.equals(email)){
                flag = true;
            }
        }
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().write("" + flag);

    }

    protected void judgeName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String name = req.getParameter("vName");

        List<User> userList = userService.findAll();
        boolean flag = false;
        for (User user : userList) {
            String username = user.getUsername();
            if (username.equals(name)){
                flag = true;
            }
        }
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().write("" + flag);

    }



    private void getPermissions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String rid = req.getParameter("rid");
        List<Permission> list = userService.findPermsByRid(rid);
        ObjectMapper mapper = new ObjectMapper();
        String permsStr = mapper.writeValueAsString(list);
        System.out.println(permsStr);
        resp.setContentType("text/json;charset=UTF-8");
        resp.getWriter().write(permsStr);
    }

        private void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Cookie[] cookies = req.getCookies();
        if (cookies.length > 0) {
            for (Cookie cookie : cookies) {
                cookie.setPath("/");
                cookie.setMaxAge(0);
                resp.addCookie(cookie);
            }
        }
        req.getSession().removeAttribute("user");
        //userService.logout(id);
        resp.sendRedirect(req.getContextPath() + "/index.jsp");
    }

    //详情页面
    protected void details (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        //获取该用户的详细信息
        User user = userService.findByUid(id);
        req.setAttribute("user",user);
        req.getRequestDispatcher("/WEB-INF/pages/system/user/user-show.jsp").forward(req, resp);
    }


    //修改状态
    protected void status(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String id = req.getParameter("id");
        User user = userService.findByUid(id);
        int status = user.getStatus();
        if (status==1){
            user.setStatus(0);
        }
        if (status==0){
            user.setStatus(1);
        }
        userService.updateMsg(user);
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().write("" + user.getStatus());

    }



    //模糊查询
    private void selectLike(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String pageNum = req.getParameter("page");
        String pageSize = req.getParameter("pageSize");

        int pageN = 1;
        int pageS = 2;
        if (pageNum != null) {
            pageN = Integer.parseInt(pageNum);
        }
        if (pageSize != null) {
            pageS = Integer.parseInt(pageSize);
        }
        String msg = req.getParameter("msg");
        List<User> list = userService.selectLike(msg,pageN,pageS);
        PageInfo<User> pageInfo = new PageInfo<User>(list);
        req.setAttribute("page",pageInfo);
        req.getRequestDispatcher("/WEB-INF/pages/system/user/user-list.jsp").forward(req,resp);
    }


    private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        User user = userService.findByUid(id);
        req.setAttribute("user", user);
        req.getRequestDispatcher("/WEB-INF/pages/update.jsp").forward(req, resp);
    }

    //更改密码
    private void edit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String newPsd = req.getParameter("newPwd");
        String id = req.getParameter("id");
        userService.update(id, newPsd);
        resp.sendRedirect(req.getContextPath() + "/index.jsp");
    }

    //建立新的用户和角色关系
    protected void addRoleToUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String userId = req.getParameter("userId");

        String[] ids = req.getParameterValues("ids");

        System.out.println(userId);
        /*for (String id : ids) {
            System.out.println(id);
        }*/
        userService.addRoleToUser(userId, ids);

        resp.sendRedirect(req.getContextPath() + "/system/user/list");

    }


    //跳转更改角色
    protected void changeRole(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取用户的id
        String id = req.getParameter("id");
        List<String> rList = userService.findRoleIdsByUid(id);
        List<Role> roleList = roleService.findAll();
        req.setAttribute("rList", rList);
        req.setAttribute("uid", id);
        req.setAttribute("roleList", roleList);
        //跳转更改角色的界面
        req.getRequestDispatcher("/WEB-INF/pages/system/user/user-role-add.jsp").forward(req, resp);
    }


    //删除
    protected void deleteById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        userService.delete(id);
        resp.sendRedirect(req.getContextPath() + "/system/user/list");
    }

    //新增
    protected void save(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        User user = BeanUtil.fillBean(req, User.class);
        userService.save(user);
        resp.sendRedirect(req.getContextPath() + "/system/user/list");
    }

    //跳转新增
    protected void toAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/pages/system/user/user-add.jsp").forward(req, resp);
    }
    //跳转首页
    protected void toMain(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/pages/home/main.jsp").forward(req, resp);
    }

    //遍历分页查询
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取当前页码数
        String pageNum = req.getParameter("page");
        String pageSize = req.getParameter("pageSize");

        int pageN = 1;
        int pageS = 3;
        if (pageNum != null) {
            pageN = Integer.parseInt(pageNum);
        }
        if (pageSize != null) {
            pageS = Integer.parseInt(pageSize);
        }

        List<User> list = userService.list(pageN, pageS);

        PageInfo<User> pageInfo = new PageInfo<User>(list);


        req.setAttribute("page", pageInfo);

//        List<User> list = userService.findAll();

//        req.setAttribute("list",list);

        req.getRequestDispatcher("/WEB-INF/pages/system/user/user-list.jsp").forward(req, resp);
    }
}
